import { dataSource } from "../../db/typeorm";
import { validatorData } from "../../db/utils";
import { Netdisk } from "../../entity/netdisk";
import { formatPage, formatPageFileterData } from "../../utils/pages";

// 创建网盘分类
export async function netdiskCreate(data: any, user_id: string) {
  const netdiskInfo = formatPageFileterData(data, [
    "file_name",
    "file_type",
    "file_status",
    "parent_id",
  ]) as unknown as Netdisk;
  netdiskInfo.file_type = "1"; // 1文件夹 2文件
  netdiskInfo.create_user = user_id;
  await validatorData(netdiskInfo, Netdisk);
  await dataSource.getRepository(Netdisk).insert(netdiskInfo);
}

// 上传文件到网盘
export async function netdiskUpload(data: any, file: any, user_id: number) {
  if (file) {
    // console.log(data, file, user_id);
    const netdiskInfo = formatPageFileterData(data, [
      "file_path",
      "file_type",
      "file_name",
      "file_status",
      "parent_id",
    ]) as unknown as Netdisk;
    netdiskInfo.create_user = String(user_id);
    netdiskInfo.file_path = file.filename;
    netdiskInfo.file_type = "2"; // 1文件夹 2文件
    netdiskInfo.file_name = file.originalname;
    await validatorData(netdiskInfo, Netdisk);
    await dataSource.getRepository(Netdisk).insert(netdiskInfo);
  } else {
    throw new Error("文件上传失败！");
  }
}

// 获取网盘列表
export async function netdiskList(params: any, user_id: number) {
  const { pageIndex, pageSize } = formatPage(params);
  const queryData = formatPageFileterData(params, ["parent_id"]);
  let querySql = dataSource.getRepository(Netdisk).createQueryBuilder();
  querySql.andWhere("parent_id = :id", { id: queryData.parent_id || 0 });
  querySql.andWhere("create_user = :user_id", { user_id });
  querySql = querySql
    .orderBy("create_time", "DESC")
    .take(pageSize)
    .skip((pageIndex - 1) * pageSize);

  const records = await querySql.getMany(); // 获取查询结果
  const total = await querySql.getCount(); // 获取符合条件的数据总数

  return { total, records };
}
